<template>
  <div class="flood-history-container">
    <!-- 左侧表单区域 -->
    <div class="form-section">
      <h3 class="form-title">请输入洪水信息</h3>
      <el-form :model="forecastForm" label-width="100px">
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="forecastForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="forecastForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>
        <el-form-item label="流域ID">
          <el-input v-model="forecastForm.basinId" placeholder="请输入流域ID" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getForecastData">流量趋势</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 右侧图表区域 -->
    <div class="chart-section">
      <div v-if="forecastChartData" class="forecast-chart-container">
        <div class="forecastChart" style="width: 100%; height: 600px;"></div>
      </div>
      <div v-else class="empty-chart">
        <el-empty description="请在左侧输入查询条件并点击流量趋势按钮" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 预测相关状态
const forecastForm = ref({
  startTime: '',
  endTime: '',
  basinId: ''
})
const forecastChartData = ref(null)
const forecastChartInstance = ref(null)

// 初始化预测图表
const initForecastChart = () => {
  if (!forecastChartData.value) return;

  const chartDom = document.querySelector('.forecastChart');
  if (!chartDom) return;

  // 处理当前时间数据、预测数据和标签数据
  const currentTimeData = forecastChartData.value.current_time_data.map(item => [item.time * 1000, item.flow]);
  const predictionsData = forecastChartData.value.predictions.map(item => [item.time * 1000, item.flow]);
  const labelData = forecastChartData.value.label_data.map(item => [item.time * 1000, item.flow]);
  const rainfallData = forecastChartData.value.current_time_data.map(item => [item.time * 1000, item.rainfall]);
  const predictedRainfallData = forecastChartData.value.predictions.map(item => [item.time * 1000, item.rainfall]);

  // 确保数据连续性
  if (currentTimeData.length > 0 && predictionsData.length > 0) {
    const lastCurrentTime = currentTimeData[currentTimeData.length - 1][0];
    const firstPredictionTime = predictionsData[0][0];
    if (lastCurrentTime !== firstPredictionTime) {
      const lastCurrentFlow = currentTimeData[currentTimeData.length - 1][1];
      predictionsData.unshift([lastCurrentTime, lastCurrentFlow]);
    }
  }

  if (currentTimeData.length > 0 && labelData.length > 0) {
    const lastCurrentTime = currentTimeData[currentTimeData.length - 1][0];
    const firstLabelTime = labelData[0][0];
    if (lastCurrentTime !== firstLabelTime) {
      const lastCurrentFlow = currentTimeData[currentTimeData.length - 1][1];
      labelData.unshift([lastCurrentTime, lastCurrentFlow]);
    }
  }

  forecastChartInstance.value = echarts.init(chartDom);
  const option = {
    title: {
      text: `流量预测趋势 - ${forecastForm.value.basinId}`,
      subtext: `${new Date(forecastChartData.value.current_time_data[0].time * 1000).toLocaleString('zh-CN')} 至 ${new Date(forecastChartData.value.label_data[forecastChartData.value.label_data.length - 1].time * 1000).toLocaleString('zh-CN')}`,
      left: 'center',
      top: 0,
      padding: [0, 0, 30, 0]
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        const time = new Date(params[0].value[0]).toLocaleString('zh-CN');
        let result = `${time}<br/>`;
        params.forEach(param => {
          let value = param.value[1];
          let unit = '';
          if (param.seriesName.includes('水位')) {
            unit = ' m';
          } else if (param.seriesName === '降雨量') {
            unit = ' mm';
          } else {
            unit = ' m³/s';
          }
          result += `${param.seriesName}: ${value}${unit}<br/>`;
        });
        return result;
      }
    },
    legend: {
      data: ['当前流量', '预测流量', '实际流量', '当前降雨量', '预测降雨量', '实际降雨量'],
      bottom: 10,
      left: 'center'
    },
    grid: {
      right: '10%',
      left: '10%',
      bottom: '15%'
    },
    xAxis: {
      type: 'time',
      axisLabel: {
        formatter: (value) => new Date(value).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' })
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '流量 (m³/s)',
        position: 'left',
        axisLine: {
          show: true
        },
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '降雨量 (mm)',
        position: 'right',
        axisLine: {
          show: true
        },
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '当前流量',
        type: 'line',
        yAxisIndex: 0,
        data: currentTimeData,
        itemStyle: {
          color: '#0076f6'
        },
        lineStyle: {
          width: 2,
        }
      },
      {
        name: '预测流量',
        type: 'line',
        yAxisIndex: 0,
        data: predictionsData,
        itemStyle: {
          color: '#41b783'
        },
        lineStyle: {
          width: 2, type: 'dashed'
        }
      },
      {
        name: '实际流量',
        type: 'line',
        yAxisIndex: 0,
        data: labelData,
        itemStyle: {
          color: '#3d97f8'
        },
        lineStyle: {
          width: 2,
        }
      },
      {
        name: '当前降雨量',
        type: 'bar',
        yAxisIndex: 1,
        data: rainfallData,
        barWidth: '60%',
        itemStyle: {
          color: '#fb8c00'
        },
        lineStyle: {
          width: 2,
        }
      },
      {
        name: '预测降雨量',
        type: 'bar',
        yAxisIndex: 1,
        data: predictedRainfallData,
        barWidth: '60%',
        itemStyle: {
          color: '#7bb69d'
        },
        lineStyle: {
          width: 2,
        }
      },
      {
        name: '实际降雨量', 
        type: 'bar',
        yAxisIndex: 1, 
        data: forecastChartData.value.label_data.map(item => [item.time * 1000, item.rainfall]),
        barWidth: '60%',
        itemStyle: { color: '#ffb74d'},
        lineStyle: { width: 2, }      
      }    
    ]  
  };

  forecastChartInstance.value.setOption(option);

  // 窗口大小变化时自适应
  window.addEventListener('resize', () => {
    forecastChartInstance.value?.resize();
  });
};

// 获取预测数据
const getForecastData = async () => {
  try {
    // 验证输入
    if (!forecastForm.value.startTime || !forecastForm.value.endTime || !forecastForm.value.basinId) {
      ElMessage.warning('请填写完整的查询信息')
      return
    }

    // 转换时间格式为Unix时间戳(秒)
    const startTime = Math.floor(new Date(forecastForm.value.startTime).getTime() / 1000)
    const endTime = Math.floor(new Date(forecastForm.value.endTime).getTime() / 1000)
    
    if (isNaN(startTime) || isNaN(endTime) || startTime >= endTime) {
      ElMessage.warning('请选择有效的时间范围')
      return
    }

    // 1. 先获取历史降雨数据
    const historyResponse = await fetch(
      `http://10.10.10.125:8002/api/history_rainfall?query=${encodeURIComponent( `${startTime} ${endTime} ${forecastForm.value.basinId}`)}`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )
    
    const historyData = await historyResponse.json()
    
    // 2. 调用预测接口
    const response = await fetch(`http://10.10.10.125:8002/api/forecast?start_datetime=${startTime}&end_datetime=${endTime}&area_id=${forecastForm.value.basinId}&top_n=3`,
      {
        method: 'POST',
        headers: {
          'accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(historyData.data) // 直接传递历史数据数组
      }
    )
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const forecastData = await response.json()
    forecastChartData.value = forecastData
    
    // 初始化预测图表
    nextTick(() => {
      initForecastChart()
    })
    
  } catch (error) {
    console.error('获取预测数据失败:', error)
    ElMessage.error(`获取预测数据失败: ${error.message}`)
  }
};
</script>

<style scoped>
.flood-history-container {
  display: flex;
  height: 100%;
  width: 100%;
}

.form-section {
  width: 20%;
  padding: 20px;
  background-color: #f5f7fa;
  border-right: 1px solid #e6e6e6;
  overflow-y: auto;
}

.form-title {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.chart-section {
  width: 80%;
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.forecast-chart-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.empty-chart {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>